<template>
  <div>
    <!-- 新增或者修改商品 -->
    <el-form
      :model="addForm"
      ref="addFormRef"
      :rules="rules"
      label-position="top"
    >
      <el-form-item label="商品编码" prop="myCode">
        <div class="w-full flex justify-between items-center">
          <el-input
            v-model.trim="addForm.myCode"
            placeholder="请输入商品编码"
            class="w-[75%] mr-1"
            :disabled="props.detailId != 0"
          />
          <el-button
            :type="props.detailId != 0 ? 'info' : 'primary'"
            :disabled="props.detailId != 0"
            :loading="code_loading"
            @click="createRandomCode"
          >
            生成随机编码
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="拼音码" prop="spelling">
        <el-input
          v-model.trim="addForm.spelling"
          placeholder="请输入拼音码"
          :disabled="props.detailId != 0"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsTitle">
        <el-input
          v-model.trim="addForm.goodsTitle"
          placeholder="请输入商品名称"
        />
      </el-form-item>
      <el-form-item label="是否上架" prop="isSelling">
        <el-radio-group v-model="addForm.isSelling">
          <el-radio-button :value="1" label="是" />
          <el-radio-button :value="2" label="否" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品种类" prop="generalId">
        <el-select
          v-model="addForm.generalId"
          placeholder="请选择商品种类"
          filterable
          @change="handleSelectCategoryList"
        >
          <el-option
            v-for="item in props.generalList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品品牌" prop="brandId">
        <el-select
          v-model="addForm.brandId"
          placeholder="请选择商品品牌"
          filterable
        >
          <el-option
            v-for="item in props.brandList"
            :key="item.id"
            :label="item.brandName"
            :value="item.id"
          />
        </el-select>

        <!-- <el-autocomplete
          v-model="addForm.brandName"
          :fetch-suggestions="querySearchBrand"
          :value-key="'brandName'"
          clearable
          placeholder="请输入检索品牌"
          @blur="handleBlurBrand"
        /> -->
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <el-select
          v-model="addForm.categoryId"
          :placeholder="
            !addForm.generalId ? '请先选择商品种类' : '请选择商品分类'
          "
          filterable
          @change="handleSelectTypeList"
          :disabled="!addForm.generalId"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.categoryName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品型号/系列" prop="typeId">
        <el-autocomplete
          v-model="addForm.typeName"
          :fetch-suggestions="querySearchCategory"
          :value-key="'typeName'"
          clearable
          :placeholder="
            !addForm.generalId
              ? '请先选择商品种类'
              : !addForm.categoryId
              ? '请先选择商品分类'
              : '请输入检索型号/系列'
          "
          :disabled="!addForm.categoryId"
          @blur="handleBlurType"
        />
      </el-form-item>
      <el-form-item label="备注" prop="description">
        <el-input
          v-model.trim="addForm.description"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
        />
      </el-form-item>
      <el-form-item label="商品图片" prop="goodsImg">
        <upload-image v-model="addForm" fileName="goodsImg" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import UploadImage from "@/components/UploadImage.vue";
import { handleApiResponse } from "@/utils/request.js";
import {
  selectBrandList,
  selectCategoryList,
  selectTypeList,
} from "@/api/api.js";
import {
  GetGoodsInfo,
  AddGoodsInfo,
  UpdateGoodsInfo,
  GenerateGoodsCode,
} from "../../../../../wailsjs/go/api/GoodsApi.js";

onMounted(() => {
  if (props.detailId != 0) {
    getDetail();
  }
});

const emit = defineEmits(["handleBack"]);
const props = defineProps({
  detailId: {
    type: Number,
    default: 0,
  },
  generalList: {
    type: Array,
    default: () => [],
  },
  brandList: {
    type: Array,
    default: () => [],
  },
});

const addFormRef = ref(null);
const addForm = ref({
  myCode: "",
  spelling: "",
  goodsTitle: "",
  isSelling: null,
  generalId: null,
  generalName: "",
  categoryId: null,
  categoryName: "",
  brandId: null,
  brandName: "",
  typeId: null,
  typeName: "",
  description: "",
  goodsImg: "",
});

const handleSubmit = () => {
  addFormRef.value.validate(async (valid) => {
    if (!valid) return;
    emit("handleBack", 1);
    addForm.value.brandName = props.brandList.find(
      (item) => item.id == addForm.value.brandId
    )?.brandName;
    addForm.value.categoryName = categoryList.value.find(
      (item) => item.id == addForm.value.categoryId
    )?.categoryName;
    if (props.detailId == 0) {
      handleApiResponse(() => AddGoodsInfo(addForm.value)).then((res) => {
        if (res.code == 0) {
          ElMessage.success("新增成功");
          emit("handleBack");
        }
        emit("handleBack");
      });
    } else {
      handleApiResponse(() => UpdateGoodsInfo(addForm.value)).then((res) => {
        if (res.code == 0) {
          ElMessage.success("修改成功");
        }
        emit("handleBack");
      });
    }
  });
};

// 获取详情
async function getDetail() {
  handleApiResponse(() => GetGoodsInfo({ id: props.detailId })).then((res) => {
    if (res.code == 0) {
      addForm.value = res.data || {};
      handleSelectCategoryList(1);
    }
  });
}

// 1.生成随机编码
const code_loading = ref(false); // 控制按钮是否加载中
let isClick = ref(false);
const createRandomCode = () => {
  if (isClick.value) {
    return ElMessage.warning("请勿频繁操作");
  }
  code_loading.value = true;
  isClick.value = true;

  handleApiResponse(() => GenerateGoodsCode()).then((res) => {
    if (res.code == 0) {
      addForm.value.myCode = res.data.myCode || "";
      code_loading.value = false;
    }
  });
  setTimeout(() => {
    isClick.value = false;
  }, 2000); // 2s后才能再次生成，防止用户连续点击
};

const categoryList = ref([]);
const typeList = ref([]);
async function handleSelectCategoryList(type) {
  // type 存在就不清空下面分类和型号
  if (!type) {
    addForm.value.categoryId = null;
    addForm.value.typeId = null;
    categoryList.value = [];
    typeList.value = [];
  }

  selectCategoryList(addForm.value.generalId).then((res) => {
    if (res.code == 0) {
      categoryList.value = res.data.list || [];
    }
  });
}
async function handleSelectTypeList() {
  addForm.value.typeId = null;
  typeList.value = [];

  selectTypeList({ id: addForm.value.categoryId }).then((res) => {
    if (res.code == 0) {
      typeList.value = res.data.list || [];
    }
  });
}

function querySearchBrand(queryString, cb) {
  let results = queryString
    ? props.brandList.filter(createFilter(queryString))
    : props.brandList;
  cb(results);
}
function querySearchCategory(queryString, cb) {
  let results = queryString
    ? typeList.value.filter(createFilter(queryString))
    : typeList.value;
  cb(results);
}
function createFilter(queryString) {
  return function (query) {
    return (
      query &&
      query.value &&
      query.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
}

const handleBlurBrand = () => {
  return;
  let found = props.brandList.find(
    (item) => item.brandName == addForm.value.brandName
  );

  if (found) {
    addForm.value.brandId = found[0].id;
  } else {
    addForm.value.brandId = 0;
  }
};
const handleBlurType = (type) => {
  if (!addForm.value.typeName) {
    addForm.value.typeId = null;
    return;
  }
  let found = typeList.value.find(
    (item) => item.typeName == addForm.value.typeName
  );

  if (found) {
    addForm.value.typeId = found[0].id;
  } else {
    addForm.value.typeId = 0;
  }
};

const rules = ref({
  myCode: [{ required: true, message: "请输入商品编码" }],
  spelling: [{ required: true, message: "请输入拼音码" }],
  goodsTitle: [{ required: true, message: "请输入商品名称" }],
  isSelling: [{ required: true, message: "请选择是否上架" }],
  generalId: [{ required: true, message: "请选择商品种类" }],
  categoryId: [{ required: true, message: "请选择商品分类" }],
  brandId: [{ required: true, message: "请选择商品品牌" }],
  typeId: [{ required: true, message: "请选择商品型号" }],
  description: [{ required: false, message: "请输入商品描述" }],
  goodsImg: [{ required: false, message: "请上传商品图片" }],
});

defineExpose({
  handleSubmit,
});
</script>

<style scoped lang="scss">
</style>